package org.deltaset.samples.library.extension;

import javax.faces.context.FacesContext;
import org.deltaset.meta.EntityResolver;
import org.deltaset.meta.extension.RepositoryProvider;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

/**
 *
 * @author dmakariev
 */
public class RepositoryProviderImpl implements RepositoryProvider {

    @Override
    public Class defaultRepositoryClass() {
        return ModelRepository.class;
    }

    @Override
    public Object locateRepository(final Class serviceClass, final Class entityClass) {
        final ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        try {

            final Object service = ctx.getBean(serviceClass);
            return service;
        } catch (NoSuchBeanDefinitionException ex) {
        } catch (BeansException ex) {
        }
        final BaseRepository baseRepository = ctx.getBean(BaseRepository.class);
        return new BaseModelRepository(baseRepository, entityClass);
    }

    @Override
    public EntityResolver createEntityResolver() {
        return new EntityResolverImpl();
    }
}
